	/*************************************************************************
	Project:    WINGS
	Overview: This do-file is for running estimates for the welfare impacts paper using the 
				panel data. See below for the brief outline 
	
	Inputs- 
	User-written program : desbal (for more details see read me file)
	HH data: wings_hh_analysis_merged_bl_ml_el

	******************************************************************************/
	clear all
	clear matrix
	set more off
	set matsize 800
	set maxvar 20000
	set memory 280m
	pause on

	if c(username) == "NKUMAR" { 		
		global root 	"C:\Users\NKUMAR\Dropbox (IFPRI)\WINGS"		
	}
	if c(username) == "GTHAI" { 		
		global root 	"C:\Users\GTHAI\Dropbox (IFPRI)\BMGF SHG-Nutrition Proposal India 2015"		
	}
	if c(username) == "shivanigupta" { 		
		global root 	"C:\Users\shivanigupta\Dropbox (IFPRI)\BMGF SHG-Nutrition Proposal India 2015"		
	}
	if c(username) == "KRAGHUNATHAN" { 		
			global root 	"C:\Users\KRAGHUNATHAN\Dropbox (IFPRI)\WINGS"	
		}

	global project_data "$root\2_PRADAN\Endline survey\09_Analysis data\03_final"
	global manuscript_dofiles "$root\Publications\Panel_WelfareImpact\3. do files"
	global manuscript_finaldata "$root\Publications\Panel_WelfareImpact\2. data\final"
	global manuscript_analysisdata "$root\Publications\Panel_WelfareImpact\2. data\analysis"
	global manuscript_output "$root\Publications\Panel_WelfareImpact\4. output"
	******************************************************************************/

	local date = string( d(`c(current_date)'), "%dCY-N-D" )
	di "`date'"

	* Setting locals for user-defined programs
	include "$manuscript_dofiles\0.1.program_WINGS_WelfareImpact.do"
	
	****************************************************************************************************

	****************************************************************************************************
	
	* Import data with merged 3 rounds
	use "$manuscript_analysisdata\WINGS_WelfareImpact.dta", clear // to add any additional variables - please go to data_prep do files
	
	cap: log close
	log using "$manuscript_dofiles\0.2.analysis_WINGS_WelfareImpact.log", text replace
	********************************************************************************
	*
	* 1. Defining globals and treatment groups
	*
	********************************************************************************

	*-------------------------------------------------------------------------------------------------------------------------------------------------*
	*-------------------------------------------------------a. Define outcome globals-----------------------------------------------------------------*
	*-------------------------------------------------------------------------------------------------------------------------------------------------*
	**(Baseline-Endline)/Endline only vars for each of the following:
		*1. Expenditure Indicators
			*P2O.1. Per capita monthly expenditure on food items
			*P2O.2. Per capita monthly expenditure on non food items
			*P2O.3. Per capita total monthly expenditure 
			*P2O.4. Per capita monthly expenditure on animal sourced food items 
		*2. Wealth Indicators
			*P2O.5. Wealth pca (does not include dwelling chars)
		*3. Assets Indicators
			*P2O.6. Total number of assets owned 
			*P2O.7. Total number of productive assets owned			
			*P2O.8. Total livestock units owned
			*P2O.9. Total number of large livestock owned
			*P2O.10.Total number of medium livestock owned
			*P2O.11.Total number of small livestock owned
	*ITN: Endline variables (for consumption variables at EL, recommended to use adjusted values as they are deflated to baseline) 
				
		** Change (DID- BL to EL) outcomes list
		* Expenditure Indicators
		#delimit; 
		gl cons_o
					d_pc_V_cons_m_adj // at the moment no missing bc when summing food and non-food, missings mentioned above = 0
					d_pc_V_nf_cons_m_adj // missing from 5 R3 HHs that have female data only
					d_pc_V_f_cons_mo_m_adj // missing from 3 R3 HHs that didn't consume any food (which didn't make sense) or don't remember quantity
					d_pc_V_af_cons_mo_m_adj;  // missing from 3 R3 HHs that didn't consume any food (which didn't make sense) or don't remember quant
		#delimit cr  

	   /*d_land_area_owned_total */ /* Outcome dropped on 2nd Nov 2020 */  
	   /*d_land_area_op_tot */ // missings come from DK answers in both rounds /* Outcome dropped on 2nd Dec 2020 */
		
		* Wealth Indicators
		gl wealth_o d_wealth_pca // missings from missing in individual assets 

		* Assets Indicators
		#delimit; 
		gl assets_o
					d_hh_total_assets // no missing 
					d_hh_total_prod_assets // no missing 
					d_tlu d_hh_large_livestock d_hh_med_livestock d_hh_small_livestock; // missings come from DK answers in both rounds
		#delimit cr  
		
		gl outvars $cons_o $wealth_o $assets_o
				
			**Temporary renaming and labelling to make R1 and R3 consistent 
			foreach r in r1 r3 {
			lab var `r'_pc_V_f_cons_mo_m_adj 	 		"Per-capita monthly food expenditure (INR)"
			lab var `r'_pc_V_nf_cons_m_adj 				"Per-capita monthly non-food expenditure (INR)"
			lab var `r'_pc_V_cons_m_adj 				"Per-capita total monthly expenditure (food and non-food) (INR)"
			lab var `r'_pc_V_af_cons_mo_m_adj			"Per-capita monthly animal-sourced food expenditure (INR)"
			}
			
			for var r3_pc_V_f_cons_mo_m_adj r3_pc_V_nf_cons_m_adj r3_pc_V_cons_m_adj r3_pc_V_af_cons_mo_m_adj: note X: Adjusted values			 	

			labvarch $outvars, subst(" BL to EL" "") 
			labvarch d_pc_V_af_cons_mo_m_adj, subst(" using modal p" "")
			labvarch d_pc_V_f_cons_mo_m_adj, subst(" using modal price" "")
			labvarch d_pc_V_f_cons_mo_m_adj d_pc_V_af_cons_mo_m_adj, suffix(" (INR)")
			labvarch $cons_o, subs("per cap" "per-capita")
			
			foreach var in $outvars {
			labvarch `var', subst("Change in " "")
					local lbl: var label `var'
					loc lbl = proper(substr("`lbl'", 1, 1)) + substr("`lbl'", 2, .)
					label var `var' "`lbl'" 
			}
			
			des $outvars
			su $outvars
		
		** Ancova outcomes list
		* Expenditure Indicators
		#delimit; 
		gl cons_o_ancova
						pc_V_cons_m_adj 		// at the moment no missing bc when summing food and non-food, missings mentioned above = 0
						pc_V_nf_cons_m_adj 		// missing from 5 R3 HHs that have female data only
						pc_V_f_cons_mo_m_adj 	// missing from 3 R3 HHs that didn't consume any food (which didn't make sense) or don't remember quantity
						pc_V_af_cons_mo_m_adj;  // missing from 3 R3 HHs that didn't consume any food (which didn't make sense) or don't remember quant	
		#delimit cr  

		* Wealth Indicators
		gl wealth_o_ancova wealth_pca // missings from missing in individual assets 

		* Assets Indicators
		#delimit; 
		gl assets_o_ancova
							hh_total_assets // no missing 
							hh_total_prod_assets // no missing 
							tlu hh_large_livestock hh_med_livestock hh_small_livestock; // missings come from DK answers in both rounds
		#delimit cr  

		gl outvars_ancova $cons_o_ancova $wealth_o_ancova $assets_o_ancova

		foreach i in $outvars_ancova{
			mdesc r3_`i'
		}				
			
	*-------------------------------------------------------------------------------------------------------------------------------------------------*
	*---------------------------------------------------------b.Define xvar globals-------------------------------------------------------------------*
	*-------------------------------------------------------------------------------------------------------------------------------------------------*
	
		* Household level
		gl respW 		r1_resp_age r1_resp_age_sq r1_w_edu r1_w_edu_sq r1_resp_emp_status 
		gl respW_alt 	r1_resp_age r1_resp_age_sq r1_w_edu r1_w_edu_sq  //KR: dropping employment status as potentially endogenous
		gl marriage 	r1_resp_married r1_resp_years_married r1_resp_mil_present r1_resp_fil_present
		gl demog 		r1_hhh_caste_ST_SC r1_hhh_caste_OBC r1_nf r1_nm r1_depratio 
		gl dwelling 	r1_hh_dwelling_score
		
		* Community level
		gl village 		r1_vil_edu_w 
		gl comm 		r1_vil_govt_primaryschool r1_vil_pvt_primaryschool r1_vil_anganwadi r1_vil_electricity r1_vil_dist_town_20
		
		* Location vars
		gl district 	r3_a04_1 r3_a04_2 r3_a04_3 r3_a04_4 r3_a04_5 r3_a04_6 r3_a04_7 /* r3_a04_8 */
		gl state 		r3_a05_1 r3_a05_2 r3_a05_3 r3_a05_4 /* r3_a05_5 */
				
		* All vars
		gl xvars 		$respW $marriage $demog $dwelling $village $comm 
		gl xvars_alt	$respW_alt $marriage $demog $village $comm  //KR: dropping employment status and dwelling characteristics as potentially endogenous
		mdesc $xvars
		su $xvars
				
		* ITN: Summary of missings of Xvars:
		* 	Village-level variables under $comm: missings from 2 unmatched communities (18 HHs) at BL
		*	The rest from missing values
	
			** Temporary renaming/labelling
			labvarch $respW $marriage, after(": ")
			labvarch $district r3_a04_8, after("==")
			foreach v of varlist $district r3_a04_8 {
			label var `v' `"`= proper("`: var label `v''")'"'
			}
			
			lab var r1_hhh_caste_ST_SC "Household head is Scheduled Tribe or Scheduled Caste"
			lab var r1_hhh_caste_OBC "Household head is OBC"
			lab var r1_nf "No. female members"
			lab var r1_nm "No. male members"
			lab var r1_vil_edu_w "Average years of education among women"
			lab var r1_vil_govt_primaryschool "Has at least one government primary school"
			lab var r1_vil_pvt_primaryschool "Has at least one private primary school"
			lab var r1_vil_anganwadi "Has at least one Anganwadi center"
			lab var r1_vil_electricity "Has electricity in all areas"
			lab var r1_vil_dist_town_20"Distance to nearest town is under 20km"
		
			foreach rec of varlist $xvars $district {
					labvarch `rec', subst(' "")
					local lbl: var label `rec'
					label var `rec' "\li114 `lbl'" // indenting labels by 0.2cms; 566=1cm 
					*ITN: Using rtf syntax to manipulate the des program for indenting or bolding, etc. 
				   }
				   
			** Generating temporary headers
			foreach v in rw marr hh_demog hh_assets hh_cons vill loc{
				gen `v'=0 // *Note: these will need to be edited manually in the tables to remove the redundant 0s and only retain the headers
			}
			
			lab var rw "{\b Respondent woman characteristics}"
			lab var hh_demog "{\b Household characteristics}"
			lab var hh_assets "{\b Household assets}"
			lab var hh_cons "{\b Household consumption}"
			lab var vill "{\b Village characteristics}"
			lab var loc "{\b Location controls}"
			
	*-------------------------------------------------------------------------------------------------------------------------------------------------*
	*-----------------------------------------------------1c. Define sample and treatments -----------------------------------------------------------*
	*-------------------------------------------------------------------------------------------------------------------------------------------------*
	
		/* NK made changes here*/
		clonevar shg_el=r3_d_shg_member
		gen shg_ml_el=0
		replace shg_ml_el= 1 if r2_d_shg_member==1 | r3_d_shg_member==1 
		clonevar shg_ml=r2_d_shg_member
		
		* a. SHG member at baseline or midline (comparison would be not an SHG member at baseline and midline)
		gen shg_bl_ml=1 if  r1_d_shg_member==1 | r2_d_shg_member==1
		replace shg_bl_ml=0 if  r1_d_shg_member==0 & r2_d_shg_member==0
		
		* b. SHG member at baseline or midline with at least 2+ years of membership (comparison would be not an SHG member at baseline and midline)
		* New version: use the variable that combines the SHG membership duration from both rounds 
		* Note on how the combination of memership duration in BL and ML was done (refer to the var creation codes in the female var creation do file):
		* Case 1: If being a member at BL but not ML: use duration of membership at BL with the assumption they stopped being a member right after BL
		* Case 2: If not being a member at BL but being a member at ML: use duration of membership at ML with a maximum of 2 years. 
		* ==> So if they said not a member at baseline but say they’ve been members for 3 years at midline, we topcode that to 2 years
		* Case 3: If being a member at both baseline and midline: select the lower of the two membership durations
		*gen shg_bl_ml2=1 if  (r1_d_shg_member==1 & r1_d_shg_member_year>=2) | (r2_d_shg_member==1 & r2_d_shg_member_year>=2) ==> original version
		gen shg_bl_ml2=1 if (r1_d_shg_member==1|r2_d_shg_member==1) & r1r2_shg_memyear >=2
		replace shg_bl_ml2=0 if  r1_d_shg_member==0 & r2_d_shg_member==0
		tab shg_bl_ml2, m
		
		/* c. SHG member =(1 if SHG member at endline, 
						   0 if (SHG member at baseline & years of membership>=2y) & (SHG member at midline & years of membership>=2y)) 
		Note: Don’t think we should use SHG membership status at endline to examine impacts at endline. 
			  However, we can consider using it in a falsification test. 
		      We measure impacts on the outcomes using this treatment definition. If SHG membership matters, then we should not find impacts. 
			  We are comparing change in outcomes for those who became members at endline with those who were members at baseline or endline and 
			  were members for at least 2 years. It will be troubling if we do find impacts using this definition.
		*/			
		clonevar shg_el2=r3_d_shg_member
		replace shg_el2=0 if (r1_d_shg_member==1  & r1_d_shg_member_year>=2) | (r2_d_shg_member==1 & r2_d_shg_member_year>=2)		
		tab2 shg_bl_ml shg_bl_ml2 shg_el2
		
		*fre shg_el shg_ml_el shg_ml shg_bl_el** Dont have this command and didnt look for it **
		
		foreach v in shg_bl_ml shg_bl_ml2 shg_el2 {
			*(i) SHG members and non-members in the overall sample all three arms pooled together
			gen S_`v'_program1=`v'
			label var S_`v'_program1 "SHG vs Non SHG"
			*(ii) SHG members vs non-members in the two PRADAN arms only 
			gen S_`v'_program2= 1 if `v'==1 & (study_arm2==1 | study_arm2==2 )
			replace S_`v'_program2= 0 if `v'==0 & (study_arm2==1 | study_arm2==2 )
			label var S_`v'_program2 "SHG vs Non SHG (PRADAN only)"
			*(iii) SHG members in a PRADAN arm (NI and Std pooled) versus SHG-members in the control arm 
			gen S_`v'_program3= 1 if `v'==1 & (study_arm2==1 | study_arm2==2)
			replace S_`v'_program3=0 if `v'==1 & study_arm2==0
			label var S_`v'_program3 "SHG (PRADAN) vs SHG (Control)"
			*(iv) SHG members in a PRADAN arm (NI and Std pooled) versus non-SHG-members in the control arm
			gen S_`v'_program4= 1 if `v'==1 & (study_arm2==1 | study_arm2==2)
			replace S_`v'_program4=0 if `v'==0 & study_arm2==0
			label var S_`v'_program4 "SHG (PRADAN) vs Non SHG (Control)"
		}

		local shg_bl_ml "Baseline or Midline SHG membership"
		local shg_bl_ml2 "Baseline or Midline SHG membership, 2 years"
		local shg_el2 "Endline SHG membership, Baseline Midline SHG members in control"
		
		local 1 "SHG vs Non SHG"
		local 2 "SHG vs Non SHG (PRADAN only)"
		local 3 "SHG (PRADAN) vs SHG (Control)"
		local 4 "SHG (PRADAN) vs Non SHG (Control)"
		
		* Make group category: 0 years, >0 & <2 years, >=2 & <=4 years, and >4 years 
		* Note on how the combination of memership duration in BL and ML was done (refer to the var creation codes in the female var creation do file):
		* Case 1: If being a member at BL but not ML: use duration of membership at BL with the assumption they stopped being a member right after BL
		* Case 2: If not being a member at BL but being a member at ML: use duration of membership at ML with a maximum of 2 years. 
		* ==> So if they said not a member at baseline but say they’ve been members for 3 years at midline, we topcode that to 2 years
		* Case 3: If being a member at both baseline and midline: select the lower of the two membership durations
		gen any_SHG_mem_group = 1 if r1r2_shg_memyear == 0
		replace any_SHG_mem_group = 2 if r1r2_shg_memyear > 0 & r1r2_shg_memyear < 2
		replace any_SHG_mem_group = 3 if r1r2_shg_memyear >= 2 & r1r2_shg_memyear <= 4
		replace any_SHG_mem_group = 4 if r1r2_shg_memyear > 4 & !missing(r1r2_shg_memyear)
		label define any_SHG_mem_group 1 "0 yrs" 2 "0-2 yrs" 3 "2-4 yrs" 4 "4+ yrs"
		label values any_SHG_mem_group any_SHG_mem_group
		label var any_SHG_mem_group "Category of SHG membership duration"
		tab any_SHG_mem_group
		
		* Restrict to PRADAN vs non-PRADAN 
		gen PRADAN = (study_arm2==1 | study_arm2==2)
		
	********************************************************************************/
	*
	* 2. Attrition analysis
	*
	*******************************************************************************			
			* Create variable for the non-attrited
			gen bl_resp_w_ffm_stay_bl_el = bl_resp_w_ffm_attr_bl_el 
			recode bl_resp_w_ffm_stay_bl_el (0=1) (1=0)
	
			**Attrition covariates 
			global union_cvars4 $xvars_alt $district
			local shg_bl_ml_t a
			local shg_bl_ml2_t b
			local shg_el2_t c
			
			*-----------------------------------------------------------------------------------------------------------------------------------------*
			*-------------------------------------------------------a. Attrition regressions----------------------------------------------------------*
			*-----------------------------------------------------------------------------------------------------------------------------------------*
			foreach s in shg_bl_ml /* shg_bl_ml2 shg_el2 */ {
			outreg, clear
				forval j=1/4 {
				frmttable, clear
				clear matrix
						* Interaction vars
						qui foreach x of varlist $union_cvars4 {
							local `x'_l: variable label `x'
							gen T_`x'_``s'_t'_`j' = `x' * S_`s'_program`j' 
							label var T_`x'_``s'_t'_`j' "Treated*``x'_l'" // `: var label S_`s'_program`j'
						}
						* Set locals for the union vars across definitions
							foreach v of varlist $union_cvars4  {
								local T_uc_``s'_t'_`j' `"`T_uc_``s'_t'_`j'' `= "T_`v'_" + "``s'_t'_`j'"'"' 
								
							}
								gl T_uc_``s'_t'_`j' `T_uc`i'_``s'_t'_`j''
								
					* Run probit (controlling for districts and clustering at block level)
						* Set base = 0 always
						fvset base 0 S_`s'_program`j' 
										
						*|without interaction|*
						xi: dprobit bl_resp_w_ffm_stay_bl_el S_`s'_program`j' $xvars_alt $district , vce(cluster r1_a03)
						outreg, store(m_``s'_t'_`j') bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se varlabels ctitle("", "Base model") 
						*|with interaction|*
						xi: dprobit bl_resp_w_ffm_stay_bl_el S_`s'_program`j' $xvars_alt $district ${T_uc_``s'_t'_`j'} , vce(cluster r1_a03)
						outreg, store(mi_``s'_t'_`j') bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se varlabels ///
									ctitle("", "Fully interacted model") 
					
						** generating pweights for interaction model
						predict wt_``s'_t'_`j', pr 
						gen pwt_``s'_t'_`j'=1/wt_``s'_t'_`j'
						label var wt_``s'_t'_`j' "Predicted probability of being in the sample at endline"
						label var pwt_``s'_t'_`j' "Inverse predicted probability of being in the sample at endline"
						
						histogram wt_``s'_t'_`j', normal kdensity xlabel(0(1)0.1)
						kdensity wt_``s'_t'_`j', plotregion(fcolor(white)) graphregion(fcolor(white))					
						graph export "$manuscript_output\graphs\attrit_``s'_t'_`j'.png", width(1600) replace

		}
		}
			
		*-------------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------b. Merged tables for each sample----------------------------------------------------------*
		*-------------------------------------------------------------------------------------------------------------------------------------------------*
		local replace replace
		foreach s in shg_bl_ml /* shg_bl_ml2 shg_el2 */ {
		outreg, replay (m_``s'_t'_1) merge(mi_``s'_t'_1) store(``s'_t'_1)
		outreg, replay (m_``s'_t'_2) merge(mi_``s'_t'_2) store(``s'_t'_2)
		outreg, replay (m_``s'_t'_3) merge(mi_``s'_t'_3) store(``s'_t'_3)
		outreg, replay (m_``s'_t'_4) merge(mi_``s'_t'_4) store(``s'_t'_4)
		forval j=1/4 {
		outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(``s'_t'_`j') 						///
				coljust(l;c) colwidth(30 10 10 10 10 10 10 10 10) basefont(fs10) statfont(fs10) landscape 				///
				note("Source: Authors' Calculation"	\					 												/// 
					 "Legend: * p<0.10; ** p<0.05; *** p<0.01")  														///
				/*multicol(1,2,2;1,4,2;1,6,2;1,8,2)*/ ctitlfont(b fs10 roman) notefont(roman fs8) titlfont(b i fs10 roman) 	///		
				title("{\b Table: Probit model predicting households staying in the sample between baseline and endline surveys (``s'') (`: var label S_`s'_program`j'')}") `replace'
		local replace addtable		
		}
		}

		*-------------------------------------------------------------------------------------------------------------------------------------------------*/
		*-------------------------------------------------------c. Drop attrited sample-------------------------------------------------------------------*
		*-------------------------------------------------------------------------------------------------------------------------------------------------*		
		* Keep the panel BL-EL sample only
		keep if bl_resp_w_ffm_attr_bl_el == 0 
		*-------------------------------------------------------------------------------------------------------------------------------------------------*		
		
		********************************************************************************/
		*
		* 3. Descriptives: General context and primary outcomes
		*
		********************************************************************************
		
		********************************************************************************************************************
		*----------3.1. Sample Descriptive table- Household characteristics at baseline (with annotation symbols)----------*
		********************************************************************************************************************		
		local replace replace
		foreach s in shg_bl_ml shg_bl_ml2 shg_el2 {
		foreach j in 1 2 3 4 { 
		preserve 		
		keep if S_`s'_program`j'!=. 
		compare S_`s'_program`j' `s' // all same except for treatment 3
			
			* Counting sample of variable by arm
			foreach t in 1 0 {
			quietly count if S_`s'_program`j'==`t' 
			local total_`t'_`j': display "`r(N)'"
			}

				* Create table using program desbal (with annotation, no sample and no observations)
				clear matrix 
				frmttable, clear
				desbal rw $respW $marriage hh_demog $demog $dwelling 															///
						vill $village $comm loc $district r3_a04_8 , arm(S_`s'_program`j') annotate store (des_`s'_`j') noobs ///
						ctitles ( "", "``s''", "" \ "", "``j''", "", \ "", "Members", "Non-members", "Difference in Means (p-val)" \ ///
											"", "(N = `total_1_`j'')", "(N = `total_0_`j'')") nosample
				
				restore
				}
/*
old code @GT: delete once seen and implemented in panel do file
				outreg, replay(des_`s'_1) merge(des_`s'_2) 
				outreg, replay(des_`s'_1) merge(des_`s'_3) 
				outreg, replay(des_`s'_1) merge(des_`s'_4) store (des_`s')			
*/
				outreg, replay(des_`s'_1) merge(des_`s'_2) store(des_`s'_a) // **Note: stored separate tables each time as KR's stata was merging only 1st and last table
				outreg, replay(des_`s'_a) merge(des_`s'_3) store(des_`s'_b)
				outreg, replay(des_`s'_b) merge(des_`s'_4) store (des_`s')			
								
				outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(des_`s') 				///
				multicol(1,2,12;2,2,3;2,5,3;2,8,3;2,11,3)  basefont(fs8 roman) statfont(fs8 roman) landscape 			///
				ctitlfont(b fs8 roman)  notefont(roman fs8) titlfont(b i fs8 roman) 									///
/*
				colwidth(25 3 3 3 3 3 3 3 3 3 3 3 3 3) */ title(Table: Summary Statistics: Baseline Covariates by SHG membership status) hlines(10001{0}1) coljust(l;c) addtable
				*local replace addtable
				}
				
	********************************************************************************/
	*
	* 4. Estimating impact -D-i-D using NN Match - comparing SHG and NON SHG HHs
	*
	********************************************************************************
		*-----------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------a. NNM Impact regressions---------------------------------------------------------------*
		*-----------------------------------------------------------------------------------------------------------------------------------------------*

		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		preserve 
			forval j=1/4 {
				outreg, clear
		foreach o in cons wealth assets {
			frmttable, clear
			clear matrix

		foreach i in ${`o'_o} {
		local `i'_a = "r3_" + substr("`i'", 3, .) // unab delta vars
				teffects nnmatch (`i' $xvars $district ) (S_`s'_program`j'), ate nneighbor(5) biasadj($xvars $district ) vce(robust, nn(5))
				su ``i'_a' if S_`s'_program`j' == 0 & e(sample)==1 // Endline Comparison Mean 
				local cm_`i': di %12.2f `r(mean)'
				local cm_`i'= strltrim("`cm_`i''") 
				outreg , bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se ///
				rtitles(`"`: var label `i''"' ) addrows("{\i Endline Comparison Mean}", "{\i `cm_`i''}" \ "{\i N}" , "{\i `e(N)'}") ctitle("`o'","S`j'") append 			
			}
			outreg, replay store(tab_`o'_`s'_`j')
			}
			
		* Appending all outcome lists
		outreg, replay(tab_cons_`s'_`j') store(tab_cons_`s'_`j'_a) addrows("{\b Wealth Indicators}")
		outreg, replay(tab_cons_`s'_`j'_a) append(tab_wealth_`s'_`j') store(tab_cons_`s'_`j'_b) addrows("{\b Asset Indicators}")
		outreg, replay(tab_cons_`s'_`j'_b) append(tab_assets_`s'_`j') store(tab_`s'_`j')
		}
		
		* Merging all 4 treatments
		outreg, replay(tab_`s'_1) merge(tab_`s'_2) store(tab_`s'_1_a)
		outreg, replay(tab_`s'_1_a) merge(tab_`s'_3) store(tab_`s'_1_b)
		outreg, replay(tab_`s'_1_b) merge(tab_`s'_4) store(tab_`s')
		restore
		}	
			
		*-------------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------b. Merged sample tables-------------------------------------------------------------------*
		*-------------------------------------------------------------------------------------------------------------------------------------------------*
		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(tab_`s') 												///
				coljust(l;c) colwidth(30 10 10 10 10 10 10 10 10) basefont(fs10) statfont(fs10) /* landscape */				///
				note("Source: Authors' Calculation"	\					 													/// 
					 "Robust standard errors in parentheses; Legend: * p<0.10; ** p<0.05; *** p<0.01")  					///
				ctitle( "", "``s''", "", "", "" \																			///
						"", "SHG vs Non SHG", "SHG vs Non SHG (PRADAN only)",												///
							"SHG (PRADAN) vs SHG (Control)", "SHG (PRADAN) vs Non SHG (Control)" \ 							///
						"Expenditure Indicators", "", "", "") 																///
				multicol(1,2,4;1,4,2) ctitlfont(b fs10 roman) notefont(roman fs8) titlfont(b i fs10 roman) 	addtable 		///		
				title("{\b Table: Nearest Neighbor Matching Impact estimates for all outcomes (DID) }") 					///
				hlines(10110000000000000001100011{0}1) 
		}
		
		
		*KR: added this in response to reviewer comments
		*-----------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------a. NNM Impact regressions---------------------------------------------------------------*
		*------------------------------------------Using alternate set of covariates as suggested by reviewers------------------------------------------*

		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		preserve 
			forval j=1/4 {
				outreg, clear
		foreach o in cons wealth assets {
			frmttable, clear
			clear matrix

		foreach i in ${`o'_o} {
		local `i'_a = "r3_" + substr("`i'", 3, .) // unab delta vars
				teffects nnmatch (`i' $xvars_alt $district ) (S_`s'_program`j'), ate nneighbor(5) biasadj($xvars_alt $district ) vce(robust, nn(5))
				su ``i'_a' if S_`s'_program`j' == 0 & e(sample)==1 // Endline Comparison Mean 
				local cm_`i': di %12.2f `r(mean)'
				local cm_`i'= strltrim("`cm_`i''") 
				outreg , bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se ///
				rtitles(`"`: var label `i''"' ) addrows("{\i Endline Comparison Mean}", "{\i `cm_`i''}" \ "{\i N}" , "{\i `e(N)'}") ctitle("`o'","S`j'") append 			
			}
			outreg, replay store(tab_`o'_`s'_`j')
			}
			
		* Appending all outcome lists
		outreg, replay(tab_cons_`s'_`j') store(tab_cons_`s'_`j'_a) addrows("{\b Wealth Indicators}")
		outreg, replay(tab_cons_`s'_`j'_a) append(tab_wealth_`s'_`j') store(tab_cons_`s'_`j'_b) addrows("{\b Asset Indicators}")
		outreg, replay(tab_cons_`s'_`j'_b) append(tab_assets_`s'_`j') store(tab_`s'_`j')
		}
		
		* Merging all 4 treatments
		outreg, replay(tab_`s'_1) merge(tab_`s'_2) store(tab_`s'_1_a)
		outreg, replay(tab_`s'_1_a) merge(tab_`s'_3) store(tab_`s'_1_b)
		outreg, replay(tab_`s'_1_b) merge(tab_`s'_4) store(tab_`s')
		restore
		}	
			
		*-------------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------b. Merged sample tables-------------------------------------------------------------------*
		*-------------------------------------------------------------------------------------------------------------------------------------------------*
		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(tab_`s') 												///
				coljust(l;c) colwidth(30 10 10 10 10 10 10 10 10) basefont(fs10) statfont(fs10) /* landscape */				///
				note("Source: Authors' Calculation"	\					 													/// 
					 "Robust standard errors in parentheses; Legend: * p<0.10; ** p<0.05; *** p<0.01")  					///
				ctitle( "", "``s''", "", "", "" \																			///
						"", "SHG vs Non SHG", "SHG vs Non SHG (PRADAN only)",												///
							"SHG (PRADAN) vs SHG (Control)", "SHG (PRADAN) vs Non SHG (Control)" \ 							///
						"Expenditure Indicators", "", "", "") 																///
				multicol(1,2,4;1,4,2) ctitlfont(b fs10 roman) notefont(roman fs8) titlfont(b i fs10 roman) 	addtable 		///		
				title("{\b Table: Nearest Neighbor Matching Impact estimates for all outcomes (DID), alternate set of covariates }") 					///
				hlines(10110000000000000001100011{0}1) 
		}
		
		
		
		
	********************************************************************************
	*
	* 5A. Estimating impact -D-i-D using IPW regression (2 rounds) 
	*
	********************************************************************************
	***Restimating pscore and generating ipw weights with xvars and district dummies***
	foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		forval j=1/4 {
			pscore S_`s'_program`j' $xvars $district, pscore(psw_`s'_`j') comsup blockid(pswblk_`s'_`j') 
			gen ipsw_`s'_`j'=. 
			qui: replace ipsw_`s'_`j'= 1/psw_`s'_`j' if S_`s'_program`j' ==1 
			qui: replace ipsw_`s'_`j'= 1/(1-psw_`s'_`j') if S_`s'_program`j' ==0 
		}
	}
		
	********************************************************************************
	* 5.1 DiD: deltaY = beta1*Treat + Xvars + district dummies
	*			deltaY is the outcomes listed above
	********************************************************************************
	outreg, clear
	frmttable, clear		
	clear mata
	scalar drop _all
			
		*-----------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------a. IPW Impact regressions---------------------------------------------------------------*
		*-----------------------------------------------------------------------------------------------------------------------------------------------*

		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		preserve 
			forval j=1/4 {
			outreg, clear
		foreach o in cons wealth assets {
		frmttable, clear
		clear matrix
		foreach i in ${`o'_o} {
		local `i'_a = "r3_" + substr("`i'", 3, .) // unab delta vars
				// without adjusting for covariates in regression (not reported in the tables!)
				reg `i' S_`s'_program`j' [pweight=ipsw_`s'_`j'], vce(robust) 
				// adjusting for covariates in regression (reported in tables!) 
				reg `i' S_`s'_program`j' $xvars $district [pweight=ipsw_`s'_`j'], vce(robust) 
				su ``i'_a' if S_`s'_program`j' == 0 & e(sample)==1 // Endline Comparison Mean 
				local cm_`i': di %12.2f `r(mean)' 
				local cm_`i'= strltrim("`cm_`i''") 
				outreg , keep(S_`s'_program`j') bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se ///
				rtitles(`"`: var label `i''"' ) addrows("{\i Endline Comparison Mean}", "{\i `cm_`i''}" \ "{\i N}" , "{\i `e(N)'}") ctitle("`o'","S`j'") append
				}
		outreg, replay store(tab_`o'_`s'_`j')
			}

		* Appending all outcome lists
		outreg, replay(tab_cons_`s'_`j') store(tab_cons_`s'_`j'_a) addrows("{\b Wealth Indicators}")
		outreg, replay(tab_cons_`s'_`j'_a) append(tab_wealth_`s'_`j') store(tab_cons_`s'_`j'_b) addrows("{\b Asset Indicators}")
		outreg, replay(tab_cons_`s'_`j'_b) append(tab_assets_`s'_`j') store(tab_`s'_`j')
		}
		
		* Merging all 4 treatments
		outreg, replay(tab_`s'_1) merge(tab_`s'_2) store(tab_`s'_1_a)
		outreg, replay(tab_`s'_1_a) merge(tab_`s'_3) store(tab_`s'_1_b)
		outreg, replay(tab_`s'_1_b) merge(tab_`s'_4) store(tab_`s')
		restore
		}	
						
*-------------------------------------------------------------------------------------------------------------------------------------------------*
*-------------------------------------------------------b. Merged sample tables-------------------------------------------------------------------*
*-------------------------------------------------------------------------------------------------------------------------------------------------*
			foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
			outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(tab_`s') 							///
					coljust(l;c) colwidth(30 10 10 10 10 10 10 10 10) basefont(fs10) statfont(fs10) /* landscape */				///
					note("Source: Authors' Calculation"	\					 													/// 
						 "Robust standard errors in parentheses; Legend: * p<0.10; ** p<0.05; *** p<0.01")  					///
					ctitle( "", "``s''", "", "", "" \																			///
							"", "SHG vs Non SHG", "SHG vs Non SHG (PRADAN only)",												///
								"SHG (PRADAN) vs SHG (Control)", "SHG (PRADAN) vs Non SHG (Control)" \ 							///
							"Expenditure Indicators", "", "", "") 																///
					multicol(1,2,4;1,4,2) ctitlfont(b fs10 roman) titlfont(b i fs10 roman) 	notefont(roman fs8) 				///		
					title("{\b Table: Inverse probability weighted regressions impact estimates for all outcomes (DID)}") 	///
					hlines(10110000000000000001100011{0}1) addtable
			}
			
			
			
	
	********************************************************************************
	*
	* 5B. Estimating impact -D-i-D using IPW regression (2 rounds): alternate set of covariates dropping those possibly endogenous
	*
	********************************************************************************
	***Restimating pscore and generating ipw weights with xvars and district dummies***
	foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		forval j=1/4 {
			pscore S_`s'_program`j' $xvars_alt $district, pscore(psw_alt_`s'_`j') comsup blockid(pswblk_alt_`s'_`j') 
			gen ipsw_alt_`s'_`j'=. 
			qui: replace ipsw_alt_`s'_`j'= 1/psw_alt_`s'_`j' if S_`s'_program`j' ==1 
			qui: replace ipsw_alt_`s'_`j'= 1/(1-psw_alt_`s'_`j') if S_`s'_program`j' ==0 
		}
	}
		
	********************************************************************************
	* 5.1 DiD: deltaY = beta1*Treat + Xvars + district dummies
	*			deltaY is the outcomes listed above
	********************************************************************************
	outreg, clear
	frmttable, clear		
	clear mata
	scalar drop _all
			
		*-----------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------a. IPW Impact regressions---------------------------------------------------------------*
		*-----------------------------------------------------------------------------------------------------------------------------------------------*

		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		preserve 
			forval j=1/4 {
			outreg, clear
			foreach o in cons wealth assets {
				frmttable, clear
				clear matrix
				foreach i in ${`o'_o} {
				local `i'_a = "r3_" + substr("`i'", 3, .) // unab delta vars
						// without adjusting for covariates in regression (not reported in the tables!)
						reg `i' S_`s'_program`j' [pweight=ipsw_alt_`s'_`j'], vce(robust) 
						// adjusting for covariates in regression (reported in tables!) 
						reg `i' S_`s'_program`j' $xvars_alt $district [pweight=ipsw_alt_`s'_`j'], vce(robust) 
						su ``i'_a' if S_`s'_program`j' == 0 & e(sample)==1 // Endline Comparison Mean 
						local cm_`i': di %12.2f `r(mean)' 
						local cm_`i'= strltrim("`cm_`i''") 
						outreg , keep(S_`s'_program`j') bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se ///
						rtitles(`"`: var label `i''"' ) addrows("{\i Endline Comparison Mean}", "{\i `cm_`i''}" \ "{\i N}" , "{\i `e(N)'}") ctitle("`o'","S`j'") append
						}
				outreg, replay store(tab_`o'_`s'_`j')
			}

			* Appending all outcome lists
			outreg, replay(tab_cons_`s'_`j') store(tab_cons_`s'_`j'_a) addrows("{\b Wealth Indicators}")
			outreg, replay(tab_cons_`s'_`j'_a) append(tab_wealth_`s'_`j') store(tab_cons_`s'_`j'_b) addrows("{\b Asset Indicators}")
			outreg, replay(tab_cons_`s'_`j'_b) append(tab_assets_`s'_`j') store(tab_`s'_`j')
		}
		
		* Merging all 4 treatments
		outreg, replay(tab_`s'_1) merge(tab_`s'_2) store(tab_`s'_1_a)
		outreg, replay(tab_`s'_1_a) merge(tab_`s'_3) store(tab_`s'_1_b)
		outreg, replay(tab_`s'_1_b) merge(tab_`s'_4) store(tab_`s')
		restore
		}	
						
*-------------------------------------------------------------------------------------------------------------------------------------------------*
*-------------------------------------------------------b. Merged sample tables-------------------------------------------------------------------*
*-------------------------------------------------------------------------------------------------------------------------------------------------*
			foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
			outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(tab_`s') 							///
					coljust(l;c) colwidth(30 10 10 10 10 10 10 10 10) basefont(fs10) statfont(fs10) /* landscape */				///
					note("Source: Authors' Calculation"	\					 													/// 
						 "Robust standard errors in parentheses; Legend: * p<0.10; ** p<0.05; *** p<0.01")  					///
					ctitle( "", "``s''", "", "", "" \																			///
							"", "SHG vs Non SHG", "SHG vs Non SHG (PRADAN only)",												///
								"SHG (PRADAN) vs SHG (Control)", "SHG (PRADAN) vs Non SHG (Control)" \ 							///
							"Expenditure Indicators", "", "", "") 																///
					multicol(1,2,4;1,4,2) ctitlfont(b fs10 roman) titlfont(b i fs10 roman) 	notefont(roman fs8) 				///		
					title("{\b Table: Inverse probability weighted regressions impact estimates for all outcomes (DID), using alternate set of covariates}") 	///
					hlines(10110000000000000001100011{0}1) addtable
			}
			
			
				
			
			
			
			
			
			
			
	********************************************************************************
	* 5.2 ANCOVA: y1 = beta1*Treat + beta2*y0 + Xvars + district dummies
	*             y1 = EL values, y0 = BL values 
	********************************************************************************
		*ITN: IPW weights from new pscore estimated with Xvars, i.e., List 5 from P0 minus state dummies plus districts dummies 	
		outreg, clear
		frmttable, clear		
		clear mata
		scalar drop _all
			
		*-----------------------------------------------------------------------------------------------------------------------------------------------*
		*-------------------------------------------------------a. ANCOVA Impact regressions------------------------------------------------------------*
		*-----------------------------------------------------------------------------------------------------------------------------------------------*

		foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
		preserve 
			forval j=1/4 {
			outreg, clear
		foreach o in cons wealth assets {
		frmttable, clear
		clear matrix
		foreach i in ${`o'_o_ancova} {
				// without adjusting for covariates in regression (not reported in the tables!)
				reg r3_`i' S_`s'_program`j'   r1_`i' [pweight=ipsw_`s'_`j'], vce(robust)
				// adjusting for covariates in regression (reported in tables!) 
				reg r3_`i' S_`s'_program`j'   r1_`i' $xvars $district [pweight=ipsw_`s'_`j'], vce(robust) 
				su r3_`i' if S_`s'_program`j'  == 0 & e(sample)==1 // Endline Comparison Mean 
				local cm_`i': di %12.2f `r(mean)' 
				local cm_`i'= strltrim("`cm_`i''") 
				outreg , keep(S_`s'_program`j' ) bdec(2 2) noautosumm starlevels(10,5,1) sigsymbols(*, **, ***) nolegend starloc(1) se ///
				rtitles(`"`: var label r3_`i''"' ) addrows("{\i Endline Comparison Mean}", "{\i `cm_`i''}" \ "{\i N}" , "{\i `e(N)'}") ctitle("`o'","S`j'") append
			}
		outreg, replay store(tab_`o'_`s'_`j')
			}

		* Appending all outcome lists
		outreg, replay(tab_cons_`s'_`j') store(tab_cons_`s'_`j'_a) addrows("{\b Wealth Indicators}")
		outreg, replay(tab_cons_`s'_`j'_a) append(tab_wealth_`s'_`j') store(tab_cons_`s'_`j'_b) addrows("{\b Asset Indicators}")
		outreg, replay(tab_cons_`s'_`j'_b) append(tab_assets_`s'_`j') store(tab_`s'_`j')
		}
		
		* Merging all 4 treatments
		outreg, replay(tab_`s'_1) merge(tab_`s'_2) store(tab_`s'_1_a)
		outreg, replay(tab_`s'_1_a) merge(tab_`s'_3) store(tab_`s'_1_b)
		outreg, replay(tab_`s'_1_b) merge(tab_`s'_4) store(tab_`s')
		restore
		}	
		
*-------------------------------------------------------------------------------------------------------------------------------------------------*
*-------------------------------------------------------b. Merged sample tables-------------------------------------------------------------------*		*-------------------------------------------------------------------------------------------------------------------------------------------------*
			foreach s in shg_bl_ml shg_bl_ml2 shg_el2  {
			outreg using "$manuscript_output\WINGS_Panel_WelfareImpact_Tables_raw_`date'.rtf", replay(tab_`s') 											///
					coljust(l;c) colwidth(30 10 10 10 10 10 10 10 10) basefont(fs10) statfont(fs10) /*landscape*/				///
					note("Source: Authors' Calculation"	\					 													/// 
						 "Robust standard errors in parentheses; Legend: * p<0.10; ** p<0.05; *** p<0.01")  					///
					ctitle( "", "``s''", "", "", "" \																			///
							"", "SHG vs Non SHG", "SHG vs Non SHG (PRADAN only)",												///
								"SHG (PRADAN) vs SHG (Control)", "SHG (PRADAN) vs Non SHG (Control)" \ 							///
							"Expenditure Indicators", "", "", "") 																///
					multicol(1,2,4;1,4,2) ctitlfont(b fs10 roman) notefont(roman fs8) titlfont(b i fs10 roman) 					///		
					title("{\b Table: Inverse Probability Weighted Regression (ANCOVA) impact estimates for all outcomes}") 	///
					hlines(10110000000000000001100011{0}1) addtable
			}
	
	
	
	
	********************************************************************************
	*
	* 6. Graphs 
	*
	********************************************************************************			
	** Figure : Change in means of outcomes by duration of membership and type of SHG
	*** Loop through several outcomes ***
		* Set globals 
		gl outvars $cons_o $wealth_o $assets_o
		gl outitles1 `""Baseline to endline change in per-capita monthly total expenditure""Baseline to endline change in per-capita monthly non-food expenditure""Baseline to endline change in per-capita monthly food expenditure""Baseline to endline change in per-capita monthly animal-sourced""Baseline to endline change in wealth PCA""Baseline to endline change in number of types of total owned assets""Baseline to endline change in number of types of owned productive assets""Baseline to endline change in tropical livestock units owned""Baseline to endline change in number of large livestock owned""Baseline to endline change in number of medium livestock owned""Baseline to endline change in number of small livestock owned""'
		gl outitles2 `""(2015 INR)""(2015 INR)""(2015 INR)""food expenditure (2015 INR)"" "" "" "" "" "" "" ""'	
		gl textline -390 -125 -280 -123 -.33 -.4 -.19 -.21 -.9 -.6 -1.4
		gl yrange `""""""""""""0(0.5)2""""""""""0(1)6""'
		local c: word count $outvars
		
		* Loops 
		forval i = 1/`c' {
		    
			local v: word `i' of $outvars
			local t1: word `i' of $outitles1
			local t2: word `i' of $outitles2
			local li: word `i' of $textline
			local yr: word `i' of $yrange
			
			* Make the group for any SHG members 
			preserve 
				local varname `v'
				local group any_SHG_mem_group 
				collapse (mean) y = `varname' (semean) se_y = `varname', by(`group')
				drop if any_SHG_mem_group == .
				
				* Add CIs
				gen yu = y + 1.96*se_y
				gen yl = y - 1.96*se_y

				* Save 
				tempfile any_shg_`i'
				save `any_shg_`i''
			restore
	
			* Make the group for non-PRADAN and PRADAN 
			preserve
				local varname `v'
				local group any_SHG_mem_group PRADAN
				collapse (mean) y = `varname' (semean) se_y = `varname', by(`group')
				drop if any_SHG_mem_group == .
				
				* Add CIs
				gen yu = y + 1.96*se_y
				gen yl = y - 1.96*se_y
				
				* Save 
				tempfile split_`i'
				save `split_`i''
			restore
	
		* Append all groups
		preserve 
			use `any_shg_`i'', clear
			append using `split_`i''
		
			* Generate separate groups
			replace PRADAN = -1 if PRADAN == .
			gsort PRADAN any_SHG_mem_group 
			gen x0 = _n
			gen x = _n
			replace x = any_SHG_mem_group  + 5 if x0 > 4
			replace x = any_SHG_mem_group  + 10 if x0 > 8
			replace PRADAN = . if PRADAN == -1
			
			* Label groups 
			label  define x 1 "0" 2 "(0-2)" 3 "[2-4]" 4 "4+"  ///
							6 "0" 7 "(0-2)" 8 "[2-4]" 9 "4+"  ///
							11 "0" 12 "(0-2)" 13 "[2-4]" 14 "4+"  
			label  value x x
			
			* Graph restricting to at least 2 years
			#delimit; 	
				twoway // Any SHG member
					   (scatter y x if PRADAN == ., msymbol(O) mc(dkgreen) mfc(dkgreen)) 
					   (rcap yu yl x if PRADAN == ., lcolor(dkgreen)) 
					   (line y x if PRADAN == ., lcolor(dkgreen))
					   // PRADAN SHG member
					   (scatter y x if PRADAN == 0, msymbol(O) mc(maroon) mfc(maroon)) 
					   (rcap yu yl x if PRADAN == 0, lcolor(maroon)) 
					   (line y x if PRADAN == 0, lcolor(maroon)) 
					   // PRADAN SHG member
					   (scatter y x if PRADAN == 1, msymbol(O) mc(navy) mfc(navy)) 
					   (rcap yu yl x if PRADAN == 1, lcolor(navy)) 
					   (line y x if PRADAN == 1, lcolor(navy)), 
					   title("`t1'" "`t2'", size(medium) span margin(medium) linegap(3))
					   xlabel(1(1)4 6(1)9 11(1)14, valuelabel labsize(small)) xtitle(" ") 
					   text(`li' 0.8 "All areas", place(e) size(small)) 
					   text(`li' 5 "non-PRADAN areas", place(e) size(small)) 
					   text(`li' 10.5 "PRADAN areas", place(e) size(small))
					   b2("Years of SHG membership", margin(medium))
					   ylabel(`yr', labsize(*0.8) angle(h))
					   ytitle(" ") yline(0, lpattern(dash) lw(thin)) legend(off) graphregion(margin(l+5 r+8) color(white));
			#delimit cr 
			gr export "$manuscript_output/graphs/P2_Welfare_var`i'.png", as(png) replace width(3000)
		restore
		} 
		
		
		
	********************************************************************************
	*
	* 7A. MDE for a given sample size using baseline means, with covariates
	*    Power 0.8 and 0.9
	*
	********************************************************************************
	*Treatments: S_shg_bl_ml_program1 S_shg_bl_ml_program2 S_shg_bl_ml_program3 S_shg_bl_ml_program4
	*Outcome variables in levels: $outvars_ancova
		
	
	foreach v in $outvars_ancova {	
		
		foreach t in S_shg_bl_ml_program1 S_shg_bl_ml_program2 S_shg_bl_ml_program3 S_shg_bl_ml_program4 {
	
			foreach power in 0.8 0.9 {													//desired power
				
				count if `t'==1
				local N_t = r(N)
				count if `t'==0
				local N_c = r(N)
				local nratio = `N_t'/`N_c'														//the ratio of experimental group to control group
				
				local alpha =0.05																//the significance level
				
				count if `t'!=.
				local N_cov= _N																	//the total sample size. 
																								

				regress r1_`v' $xvars_alt 														//using baseline control variables

				local res_sd = round(sqrt(`e(rss)'/`e(df_r)'),0.0001)							//this is the new standard deviation for the power calculation or the residual sd not explained by the control(s). 
																								//This will be used for power calculation.
					
				quietly sum r1_`v' if  !missing(r1_`v')					   						//sum the outcome at baseline and record the mean and the standard deviation
				local baseline = `r(mean)'
					
				power twomeans `baseline', n(`N_cov') power(`power') sd(`res_sd') nratio(`nratio') alpha(`alpha')  table 
					
				local mde_cov= round(`r(delta)',0.0001)

				di as error "The MDE for outcome `v' (baseline values) is `mde_cov' given treatment definition `t', a total sample size of `N_cov', ratio of treatment and control group of `nratio', power `power', and the residual standard deviation of `res_sd' after accounting for covariates."
				
			}
		
		}
	}
		
	
	********************************************************************************
	*
	* 7B. MDE for a given sample size using endline means, with covariates 
	*    Power 0.8 and 0.9
	*
	********************************************************************************
	*Treatments: S_shg_bl_ml_program1 S_shg_bl_ml_program2 S_shg_bl_ml_program3 S_shg_bl_ml_program4
	*Outcome variables in levels: $outvars_ancova
		
	
	foreach v in $outvars_ancova {	
		
		foreach t in S_shg_bl_ml_program1 S_shg_bl_ml_program2 S_shg_bl_ml_program3 S_shg_bl_ml_program4 {
	
			foreach power in 0.8 0.9 {													//desired power
				
				count if `t'==1
				local N_t = r(N)
				count if `t'==0
				local N_c = r(N)
				local nratio = `N_t'/`N_c'														//the ratio of experimental group to control group
				
				local alpha =0.05																//the significance level
				
				count if `t'!=.
				local N_cov= _N																	//the total sample size. 
																								

				regress r3_`v' $xvars_alt 														//using baseline control variables

				local res_sd = round(sqrt(`e(rss)'/`e(df_r)'),0.0001)							//this is the new standard deviation for the power calculation or the residual sd not explained by the control(s). 
																								//This will be used for power calculation.
					
				quietly sum r3_`v' if  !missing(r3_`v')					   						//sum the outcome at baseline and record the mean and the standard deviation
				local endline = `r(mean)'
					
				power twomeans `endline', n(`N_cov') power(`power') sd(`res_sd') nratio(`nratio') alpha(`alpha')  table 
					
				local mde_cov= round(`r(delta)',0.0001)

				di as error "The MDE for outcome `v' (endline values) is `mde_cov' given treatment definition `t', a total sample size of `N_cov', ratio of treatment and control group of `nratio', power `power', and the residual standard deviation of `res_sd' after accounting for covariates."
				
			}
		
		}
	}
		
		
		
		
		log close
		exit
				
		***********************************************************end of do file********************************************************************	